package org.jl.demo.authority.init;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.jl.demo.authority.model.bo.Function;
import org.jl.demo.util.ClassFileUtil;
import org.jl.demo.util.SqlUtil;
import org.jl.demo.util.YamlUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class AuthorityInit {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @PostConstruct
    public void init() {
        Map<String, Object> authority = YamlUtil.getYmlData("authority");
        ClassFileUtil util = new ClassFileUtil(null, authority);
        for (String functionName : util.functionMap.keySet()) {
            Function function = util.functionMap.get(functionName);
            String tableName = util.getTableName(functionName);
            if (ObjectUtils.isNotEmpty(function.getInit())) {
                List<Map<String, Object>> initList = function.getInit();
                Map<String, Object> firstInit = initList.getFirst();
                String[] columnStr = SqlUtil.getInsertColumnStr(firstInit);

                for (Map<String, Object> init : initList) {
                    if (init.containsKey("id") && init.get("id") != null) {
                        int id = Integer.parseInt(init.get("id").toString());
                        int count = jdbcTemplate.queryForObject(SqlUtil.getCountSql(tableName, id), Integer.class, id);
                        if (count == 0) {
                            jdbcTemplate.update(SqlUtil.getInsertSql(tableName, columnStr),
                                    SqlUtil.getValues(init, function.getField()));
                        }
                    }
                }
            }
        }
    }
}
